// 测试词汇页面逻辑
document.addEventListener('DOMContentLoaded', async () => {
  // 初始化数据
  try {
    await WordData.initializeData();
    // console.log('Test page data initialized successfully');
  } catch (error) {
    // console.error('Failed to initialize test page data:', error);
  }
  // DOM 元素
  const tabBtns = document.querySelectorAll('.tab-btn');
  const tabContents = document.querySelectorAll('.tab-content');
  const statsText = document.getElementById('stats-text');
  const timerText = document.getElementById('timer-text');
  const resetBtn = document.getElementById('reset-btn');
  const resultsModal = document.getElementById('results-modal');
  const wordCountSelect = document.getElementById('word-count-select');
  const wordCountMessage = document.getElementById('word-count-message');
  
  // 测试状态
  let currentTab = 'random';
  let currentWordIndex = 0;
  let currentWords = [];
  // 实际测试的单词列表
  let testWords = [];
  let testHistory = [];
  let correctAnswers = 0;
  let totalAnswers = 0;
  let startTime = null;
  let timerInterval = null;
  let isTestStarted = false;
  // 当前题目是否已回答
  let hasAnswered = false;
  
  /**
   * 获取当前选择的测试单词数量
   * @returns {number} 返回选择的单词数量，-1表示全部单词
   */
  const getSelectedWordCount = () => {
    const value = wordCountSelect.value;
    return value === 'all' ? -1 : parseInt(value);
  };
  
  /**
   * 显示单词数量提示消息
   * @param {string} message - 提示消息内容
   */
  const showWordCountMessage = (message) => {
    wordCountMessage.textContent = message;
    wordCountMessage.classList.remove('hidden');
    
    // 2秒后自动隐藏
    setTimeout(() => {
      wordCountMessage.classList.add('hidden');
    }, 2000);
  };
  
  /**
   * 检查用户登录状态
   * @returns {boolean} 是否已登录
   */
  const checkLoginStatus = () => {
    try {
      // 优先检查localStorage（记住登录状态）
      let userStr = localStorage.getItem('user');
      let isLoggedIn = localStorage.getItem('isLoggedIn');
      
      // 如果localStorage中没有，检查sessionStorage（临时登录）
      if (!userStr || isLoggedIn !== 'true') {
        userStr = sessionStorage.getItem('user');
        isLoggedIn = sessionStorage.getItem('isLoggedIn');
      }
      
      return userStr && isLoggedIn === 'true';
    } catch (error) {
      // console.error('Failed to check login status:', error);
      return false;
    }
  };
  
  /**
   * 获取当前用户信息
   * @returns {Object|null} 返回用户信息或null
   */
  const getCurrentUser = () => {
    try {
      // 优先从localStorage获取用户信息
      let userStr = localStorage.getItem('user');
      
      // 如果localStorage中没有，从sessionStorage获取
      if (!userStr) {
        userStr = sessionStorage.getItem('user');
      }
      
      return userStr ? JSON.parse(userStr) : null;
    } catch (error) {
      // console.error('Failed to parse user data:', error);
      return null;
    }
  };
  
  /**
   * 更新导航栏用户显示
   */
  const updateNavbarUserDisplay = () => {
    const navLogin = document.getElementById('nav-login');
    const userDropdown = document.getElementById('user-dropdown');
    const navUsername = document.getElementById('nav-username');
    const navUserAvatar = document.getElementById('nav-user-avatar');
    
    if (checkLoginStatus()) {
      const user = getCurrentUser();
      if (user && navLogin && userDropdown && navUsername) {
        navLogin.style.display = 'none';
        userDropdown.style.display = 'block';
        navUsername.textContent = user.nickname;
        
        // 设置导航栏头像
        if (navUserAvatar) {
          if (user.avatar && user.avatar !== 'img/default-avatar.png') {
            // 如果是上传的头像，添加时间戳防止缓存
            const avatarUrl = user.avatar.startsWith('img/') ? `../${user.avatar}` : user.avatar;
             const finalAvatarUrl = `${avatarUrl}?t=${Date.now()}`;
            
            navUserAvatar.src = finalAvatarUrl;
            
            // 添加错误处理
            navUserAvatar.onerror = () => {
              console.warn('⚠️ [Test页面] 头像加载失败，使用默认头像:', avatarUrl);
              navUserAvatar.src = '../img/default-avatar.png';
              navUserAvatar.onerror = null;
            };
          } else {
              navUserAvatar.src = '../img/default-avatar.png';
            }
        }
      }
    } else {
      if (navLogin && userDropdown) {
        navLogin.style.display = 'block';
        userDropdown.style.display = 'none';
      }
    }
  };
  
  /**
   * 用户登出
   */
  const logout = () => {
    // 清除localStorage中的登录信息
    localStorage.removeItem('user');
    localStorage.removeItem('isLoggedIn');
    localStorage.removeItem('rememberLogin');
    
    // 清除sessionStorage中的登录信息
    sessionStorage.removeItem('user');
    sessionStorage.removeItem('isLoggedIn');
    
    updateNavbarUserDisplay();
    
    // 跳转到登录页面
    window.location.href = 'account.html';
  };
  
  /**
   * 初始化测试页面
   */
  const init = async () => {
    setupEventListeners();
    updateNavbarUserDisplay();
    resetBtn.textContent = '开始测试';
    await loadCurrentTab();
  };
  
  /**
   * 设置事件监听器
   */
  const setupEventListeners = () => {
    // Tab切换事件
    tabBtns.forEach(btn => {
      btn.addEventListener('click', async () => {
        const tabName = btn.dataset.tab;
        await switchTab(tabName);
      });
    });
    
    // 导航按钮事件
    ['random', 'unmemorized', 'memorized', 'fill-blank'].forEach(type => {
      const prevBtn = document.getElementById(`${type}-prev`);
      const nextBtn = document.getElementById(`${type}-next`);
      
      prevBtn.addEventListener('click', () => navigateWord(type, -1));
      nextBtn.addEventListener('click', () => navigateWord(type, 1));
    });
    
    // 单词数量选择框事件
    wordCountSelect.addEventListener('change', async () => {
      if (!isTestStarted) {
        await loadCurrentTab();
      }
    });
    
    // 重新测试按钮
    resetBtn.addEventListener('click', async () => {
      if (resetBtn.textContent === '开始测试') {
        await startTest();
      } else {
        resetTest();
      }
    });
    
    // 结果模态框按钮
    document.getElementById('restart-test').addEventListener('click', () => {
      closeResultsModal();
      resetTest();
    });
    
    document.getElementById('close-results').addEventListener('click', closeResultsModal);
    
    // 用户下拉菜单事件
    const logoutBtn = document.getElementById('logout-btn');
    if (logoutBtn) {
      logoutBtn.addEventListener('click', logout);
    }
  };
  
  /**
   * 切换测试标签页
   * @param {string} tabName - 标签页名称 ('random', 'unmemorized', 'memorized', 'fill-blank')
   */
  const switchTab = async (tabName) => {
    // 更新Tab按钮状态
    tabBtns.forEach(btn => {
      btn.classList.toggle('active', btn.dataset.tab === tabName);
    });
    
    // 更新Tab内容显示
    tabContents.forEach(content => {
      content.classList.toggle('active', content.id === `${tabName}-tab`);
    });
    
    currentTab = tabName;
    currentWordIndex = 0;
    
    // 重置统计数据和按钮状态
    stopTimer();
    correctAnswers = 0;
    totalAnswers = 0;
    testHistory = [];
    startTime = null;
    isTestStarted = false;
    hasAnswered = false;
    timerText.textContent = '测试用时：00:00:00';
    resetBtn.textContent = '开始测试';
    
    // 重置select控件状态
    wordCountSelect.disabled = false;
    
    // 根据tab类型设置默认测试数量
    if (tabName === 'fill-blank') {
      wordCountSelect.value = '10'; // 选择填空默认10个
    } else {
      wordCountSelect.value = '20'; // 其他tab默认20个
    }
    
    await loadCurrentTab();
  };
  
  /**
   * 加载当前标签页的内容
   */
  const loadCurrentTab = async () => {
    let allWords = WordData.getAllWords();
    
    // 如果缓存为空，尝试刷新数据
    if (!allWords || allWords.length === 0) {
      try {
        allWords = await WordData.refreshCache();
      } catch (error) {
        // console.error('Failed to refresh data in test page:', error);
        allWords = [];
      }
    }
    
    switch (currentTab) {
      case 'random':
        currentWords = allWords;
        break;
      case 'unmemorized':
        currentWords = allWords.filter(word => !word.memorized);
        break;
      case 'memorized':
        currentWords = allWords.filter(word => word.memorized);
        break;
      case 'fill-blank':
        // 选择填空只使用有例句的单词
        currentWords = allWords.filter(word => word.example && word.example.trim());
        break;
    }
    
    // 根据选择的数量选择测试单词
    const selectedCount = getSelectedWordCount();
    
    if (selectedCount > 0) {
      if (currentWords.length < selectedCount) {
        // 单词数量不足，切换为全部单词
        wordCountSelect.value = 'all';
        testWords = [...currentWords];
        showWordCountMessage(`单词不足${selectedCount}个，已为你切换为全部单词选项`);
      } else {
        // 随机选择指定数量的单词
        const shuffled = [...currentWords].sort(() => Math.random() - 0.5);
        testWords = shuffled.slice(0, selectedCount);
      }
    } else {
      // 选择全部单词
      testWords = [...currentWords];
    }
    
    currentWordIndex = 0;
    updateStats();
    updateNavigationButtons();
    
    if (testWords.length === 0) {
      showNoWordsMessage();
    } else if (resetBtn.textContent === '开始测试') {
      showInitialState();
    } else {
      showCurrentWord();
    }
  };
  
  /**
   * 更新统计信息显示
   */
  const updateStats = () => {
    const tabNames = {
      'random': '随机测试',
      'unmemorized': '未记住的单词',
      'memorized': '已记住的单词',
      'fill-blank': '选择填空'
    };
    
    if (testWords.length === 0) {
      statsText.textContent = `${tabNames[currentTab]}：暂无可测试的单词`;
    } else {
      const accuracy = totalAnswers > 0 ? Math.round((correctAnswers / totalAnswers) * 100) : 0;
      const maxCount = testWords.length;
      
      statsText.textContent = `${tabNames[currentTab]}：${totalAnswers}/${maxCount} | 正确率：${accuracy}% (${correctAnswers}/${totalAnswers})`;
    }
  };
  
  /**
   * 开始计时器
   */
  const startTimer = () => {
    if (!startTime && !timerInterval) {
      startTime = new Date();
      timerInterval = setInterval(updateTimer, 1000);
    }
  };
  
  /**
   * 更新计时器显示
   */
  const updateTimer = () => {
    if (startTime) {
      const elapsed = Math.floor((new Date() - startTime) / 1000);
      const hours = Math.floor(elapsed / 3600);
      const minutes = Math.floor((elapsed % 3600) / 60);
      const seconds = elapsed % 60;
      
      timerText.textContent = `测试用时：${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    }
  };
  
  /**
   * 停止计时器
   */
  const stopTimer = () => {
    if (timerInterval) {
      clearInterval(timerInterval);
      timerInterval = null;
    }
  };
  
  /**
   * 开始测试
   */
  const startTest = async () => {
    isTestStarted = true;
    resetBtn.textContent = '重新测试';
    wordCountSelect.disabled = true; // 禁用选择框
    
    // 立即启动计时器
    startTimer();
    
    await loadCurrentTab();
  };
  
  /**
   * 重置测试状态
   */
  const resetTest = () => {
    wordCountSelect.disabled = false; // 启用选择框
    stopTimer();
    currentWordIndex = 0;
    correctAnswers = 0;
    totalAnswers = 0;
    testHistory = [];
    startTime = null;
    isTestStarted = false;
    hasAnswered = false;
    timerText.textContent = '测试用时：00:00:00';
    resetBtn.textContent = '开始测试';
    showInitialState();
  };
  
  // 显示当前单词
  const showCurrentWord = () => {
    if (testWords.length === 0) return;
    
    const targetWord = testWords[currentWordIndex];
    
    // 检查是否已经回答过这个单词
    const existingAnswer = testHistory.find(h => h.word.id === targetWord.id);
    hasAnswered = !!existingAnswer;
    
    const wordDisplay = document.getElementById(`${currentTab}-word`);
    wordDisplay.className = 'word-display';
    
    if (currentTab === 'fill-blank') {
      // 选择填空模式：显示处理后的例句
      const fillBlankData = generateFillBlankQuestion(targetWord, existingAnswer);
      wordDisplay.innerHTML = `
        <div class="fill-blank-container">
          <div class="sentence-text">${fillBlankData.sentence}</div>
          <div class="translation-text">${fillBlankData.translation}</div>
        </div>
      `;
      
      // 生成选择填空的选项
      generateFillBlankOptions(targetWord, fillBlankData.correctAnswer, existingAnswer);
    } else {
      // 普通模式：显示单词和读音
      wordDisplay.innerHTML = `
        <div class="word-container">
          <span class="word-text">${targetWord.word}</span>
          <span class="pronunciation">/${targetWord.pronunciation}/</span>
        </div>
      `;
      
      // 生成选项
      generateOptions(targetWord, existingAnswer);
    }
    
    // 更新导航按钮
    updateNavigationButtons();
    
    // 注意：计时器已在startTest函数中启动，这里不需要重复启动
  };
  
  /**
   * 生成选择填空题目
   * @param {Object} targetWord - 目标单词对象
   * @param {Object} existingAnswer - 已存在的答案（如果有）
   * @returns {Object} 包含处理后的句子、翻译和正确答案的对象
   */
  const generateFillBlankQuestion = (targetWord, existingAnswer = null) => {
    if (existingAnswer && existingAnswer.fillBlankData) {
      return existingAnswer.fillBlankData;
    }
    
    let example = targetWord.example || '';
    let correctAnswer = targetWord.word;
    
    // 分离英文句子和中文翻译
    const parts = example.split('\n').filter(part => part.trim());
    let englishSentence = parts[0] || example;
    let chineseTranslation = parts[1] || '';
    
    // 尝试在句子中找到目标单词
    const wordRegex = new RegExp(`\\b${targetWord.word}\\b`, 'gi');
    let processedSentence = englishSentence;
    
    if (wordRegex.test(englishSentence)) {
      // 找到了目标单词，替换为下划线
      processedSentence = englishSentence.replace(wordRegex, '______');
    } else {
      // 没找到目标单词，随机选择一个单词作为答案
      const words = englishSentence.match(/\b[a-zA-Z]{2,}\b/g) || [];
      const validWords = words.filter(word => 
        word.length > 1 && 
        !/^\d+$/.test(word) && 
        !['the', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by'].includes(word.toLowerCase())
      );
      
      if (validWords.length > 0) {
        const randomWord = validWords[Math.floor(Math.random() * validWords.length)];
        correctAnswer = randomWord;
        const randomWordRegex = new RegExp(`\\b${randomWord}\\b`, 'gi');
        processedSentence = englishSentence.replace(randomWordRegex, '______');
      } else {
        // 如果没有合适的单词，使用原单词
        processedSentence = englishSentence + ' (______)';
      }
    }
    
    return {
      sentence: processedSentence,
      translation: chineseTranslation,
      correctAnswer: correctAnswer.toLowerCase()
    };
  };
  
  /**
   * 生成选择填空的选项
   * @param {Object} targetWord - 目标单词对象
   * @param {string} correctAnswer - 正确答案
   * @param {Object} existingAnswer - 已存在的答案（如果有）
   */
  const generateFillBlankOptions = (targetWord, correctAnswer, existingAnswer = null) => {
    const allWords = WordData.getAllWords();
    const optionsContainer = document.getElementById(`${currentTab}-options`);
    
    let allOptions;
    
    if (existingAnswer && existingAnswer.allOptions) {
      // 如果已经回答过，使用之前的选项顺序
      allOptions = existingAnswer.allOptions;
    } else {
      // 获取3个错误选项
      const wrongOptions = [];
      const availableWords = allWords.filter(word => 
        word.word.toLowerCase() !== correctAnswer.toLowerCase() &&
        word.word.length > 1
      );
      
      while (wrongOptions.length < 3 && availableWords.length > 0) {
        const randomIndex = Math.floor(Math.random() * availableWords.length);
        const wrongWord = availableWords.splice(randomIndex, 1)[0];
        wrongOptions.push(wrongWord.word);
      }
      
      // 组合所有选项
      allOptions = [correctAnswer, ...wrongOptions];
      
      // 随机排序
      for (let i = allOptions.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [allOptions[i], allOptions[j]] = [allOptions[j], allOptions[i]];
      }
    }
    
    // 生成选项按钮
    optionsContainer.innerHTML = '';
    allOptions.forEach((option, index) => {
      const button = document.createElement('button');
      button.className = 'option-btn';
      button.textContent = option;
      
      // 如果已经回答过，恢复按钮状态
      if (existingAnswer) {
        button.disabled = true;
        if (option.toLowerCase() === correctAnswer.toLowerCase()) {
          button.classList.add('correct');
        } else if (option === existingAnswer.selectedOption && !existingAnswer.isCorrect) {
          button.classList.add('incorrect');
        }
      } else {
        button.addEventListener('click', () => checkFillBlankAnswer(button, option, correctAnswer, allOptions, targetWord));
      }
      
      optionsContainer.appendChild(button);
    });
  };
  
  /**
   * 检查选择填空答案
   * @param {HTMLElement} button - 被点击的按钮
   * @param {string} selectedOption - 选择的选项
   * @param {string} correctAnswer - 正确答案
   * @param {Array} allOptions - 所有选项
   * @param {Object} targetWord - 目标单词对象
   */
  const checkFillBlankAnswer = (button, selectedOption, correctAnswer, allOptions, targetWord) => {
    // 防止重复回答
    if (hasAnswered) return;
    
    const optionsContainer = document.getElementById(`${currentTab}-options`);
    const allButtons = optionsContainer.querySelectorAll('.option-btn');
    
    hasAnswered = true;
    
    // 禁用所有按钮
    allButtons.forEach(btn => btn.disabled = true);
    
    const isCorrect = selectedOption.toLowerCase() === correctAnswer.toLowerCase();
    
    // 标记正确和错误答案
    allButtons.forEach(btn => {
      if (btn.textContent.toLowerCase() === correctAnswer.toLowerCase()) {
        btn.classList.add('correct');
      } else if (btn === button && !isCorrect) {
        btn.classList.add('incorrect');
      }
    });
    
    // 更新统计
    totalAnswers++;
    if (isCorrect) {
      correctAnswers++;
    }
    
    // 记录答题历史
    const fillBlankData = generateFillBlankQuestion(targetWord);
    testHistory.push({
      word: targetWord,
      selectedOption,
      isCorrect,
      allOptions,
      fillBlankData
    });
    
    updateStats();
    updateNavigationButtons();
    
    // 如果是最后一题，显示完成测试的提示
    if (totalAnswers >= testWords.length) {
      setTimeout(() => {
        showResults();
      }, 1500);
    }
  };

  // 生成选项
  const generateOptions = (targetWord, existingAnswer = null) => {
    const allWords = WordData.getAllWords();
    const optionsContainer = document.getElementById(`${currentTab}-options`);
    
    let allOptions;
    
    if (existingAnswer && existingAnswer.allOptions) {
      // 如果已经回答过，使用之前的选项顺序
      allOptions = existingAnswer.allOptions;
    } else {
      // 获取3个错误选项
      const wrongOptions = [];
      const availableWords = allWords.filter(word => word.id !== targetWord.id);
      
      while (wrongOptions.length < 3 && availableWords.length > 0) {
        const randomIndex = Math.floor(Math.random() * availableWords.length);
        const wrongWord = availableWords.splice(randomIndex, 1)[0];
        wrongOptions.push(wrongWord.translation);
      }
      
      // 组合所有选项
      allOptions = [targetWord.translation, ...wrongOptions];
      
      // 随机排序
      for (let i = allOptions.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [allOptions[i], allOptions[j]] = [allOptions[j], allOptions[i]];
      }
    }
    
    // 生成选项按钮
    optionsContainer.innerHTML = '';
    allOptions.forEach((option, index) => {
      const button = document.createElement('button');
      button.className = 'option-btn';
      button.textContent = option;
      
      // 如果已经回答过，恢复按钮状态
      if (existingAnswer) {
        button.disabled = true;
        if (option === targetWord.translation) {
          button.classList.add('correct');
        } else if (option === existingAnswer.selectedOption && !existingAnswer.isCorrect) {
          button.classList.add('incorrect');
        }
      } else {
        button.addEventListener('click', () => checkAnswer(button, option, targetWord.translation, allOptions));
      }
      
      optionsContainer.appendChild(button);
    });
  };
  
  // 检查答案
  const checkAnswer = (button, selectedOption, correctAnswer, allOptions) => {
    // 防止重复回答
    if (hasAnswered) return;
    
    const optionsContainer = document.getElementById(`${currentTab}-options`);
    const allButtons = optionsContainer.querySelectorAll('.option-btn');
    
    hasAnswered = true;
    
    // 禁用所有按钮并显示正确答案
    allButtons.forEach(btn => {
      btn.disabled = true;
      if (btn.textContent === correctAnswer) {
        btn.classList.add('correct');
      } else if (btn === button && selectedOption !== correctAnswer) {
        btn.classList.add('incorrect');
      }
    });
    
    // 检查是否已经回答过这个单词（防止重复计数）
    const existingAnswerIndex = testHistory.findIndex(h => h.word.id === testWords[currentWordIndex].id);
    
    if (existingAnswerIndex === -1) {
      // 首次回答，更新统计
      totalAnswers++;
      if (selectedOption === correctAnswer) {
        correctAnswers++;
      }
      
      // 记录测试历史
      testHistory.push({
        word: testWords[currentWordIndex],
        selectedOption,
        correctAnswer,
        isCorrect: selectedOption === correctAnswer,
        timestamp: new Date(),
        allOptions: allOptions
      });
    } else {
      // 重新回答，更新现有记录
      const oldAnswer = testHistory[existingAnswerIndex];
      
      // 更新统计（移除旧答案的影响，添加新答案）
      if (oldAnswer.isCorrect && selectedOption !== correctAnswer) {
        correctAnswers--;
      } else if (!oldAnswer.isCorrect && selectedOption === correctAnswer) {
        correctAnswers++;
      }
      
      // 更新历史记录
      testHistory[existingAnswerIndex] = {
        word: testWords[currentWordIndex],
        selectedOption,
        correctAnswer,
        isCorrect: selectedOption === correctAnswer,
        timestamp: new Date(),
        allOptions: allOptions
      };
    }
    
    updateStats();
    updateNavigationButtons();
  };
  
  // 更新导航按钮状态
  const updateNavigationButtons = () => {
    const prevBtn = document.getElementById(`${currentTab}-prev`);
    const nextBtn = document.getElementById(`${currentTab}-next`);
    
    // 上一个按钮：第一题时禁用
    prevBtn.disabled = currentWordIndex === 0;
    
    // 下一个按钮：最后一题时显示为"完成"
    if (currentWordIndex === testWords.length - 1) {
      nextBtn.textContent = '完成';
      // 只有回答后才能完成
      nextBtn.disabled = !hasAnswered;
    } else {
      nextBtn.textContent = '下一个';
      // 只有回答后才能下一个
      nextBtn.disabled = !hasAnswered;
    }
  };
  
  // 导航到上一个/下一个单词
  const navigateWord = (type, direction) => {
    if (testWords.length === 0) return;
    
    // 下一个
    if (direction === 1) {
      if (currentWordIndex === testWords.length - 1) {
        // 最后一题，显示结果
        showResults();
        return;
      } else {
        currentWordIndex++;
      }
    // 上一个
    } else if (direction === -1) {
      if (currentWordIndex > 0) {
        currentWordIndex--;
      }
    }
    
    showCurrentWord();
  };
  
  // 显示测试结果
  const showResults = () => {
    stopTimer();
    
    const elapsed = startTime ? Math.floor((new Date() - startTime) / 1000) : 0;
    const hours = Math.floor(elapsed / 3600);
    const minutes = Math.floor((elapsed % 3600) / 60);
    const seconds = elapsed % 60;
    const timeString = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    
    const accuracy = totalAnswers > 0 ? Math.round((correctAnswers / totalAnswers) * 100) : 0;
    const incorrectCount = totalAnswers - correctAnswers;
    
    // 更新结果模态框
    document.getElementById('correct-count').textContent = correctAnswers;
    document.getElementById('incorrect-count').textContent = incorrectCount;
    document.getElementById('accuracy-rate').textContent = `${accuracy}%`;
    document.getElementById('test-duration').textContent = timeString;
    
    // 显示模态框
    resultsModal.style.display = 'flex';
  };
  
  // 关闭结果模态框
  const closeResultsModal = () => {
    resultsModal.style.display = 'none';
  };
  
  // 显示初始状态
  const showInitialState = () => {
    const wordDisplay = document.getElementById(`${currentTab}-word`);
    const optionsContainer = document.getElementById(`${currentTab}-options`);
    
    wordDisplay.textContent = '点击"开始测试"开始';
    wordDisplay.className = 'word-display initial-text';
    optionsContainer.innerHTML = '';
    
    // 禁用导航按钮
    const prevBtn = document.getElementById(`${currentTab}-prev`);
    const nextBtn = document.getElementById(`${currentTab}-next`);
    prevBtn.disabled = true;
    nextBtn.disabled = true;
    nextBtn.textContent = '下一个';
  };
  
  // 显示无单词消息
  const showNoWordsMessage = () => {
    const wordDisplay = document.getElementById(`${currentTab}-word`);
    const optionsContainer = document.getElementById(`${currentTab}-options`);
    
    wordDisplay.textContent = '暂无可测试的单词';
    optionsContainer.innerHTML = '<p style="color: #666; font-size: 18px; grid-column: 1 / -1; text-align: center;">请先添加一些单词或调整记忆状态</p>';
    
    // 禁用导航按钮
    const prevBtn = document.getElementById(`${currentTab}-prev`);
    const nextBtn = document.getElementById(`${currentTab}-next`);
    prevBtn.disabled = true;
    nextBtn.disabled = true;
    nextBtn.textContent = '下一个';
  };
  
  // 导航栏事件处理
  const navLinks = document.querySelectorAll('.nav-link');
  navLinks.forEach(link => {
    link.addEventListener('click', (e) => {
      const page = link.dataset.page;
      if (page === 'about') {
        e.preventDefault();
        alert('关于我们功能正在开发中...');
      }
    });
  });
  
  // 初始化应用
  await init();
});